package com.shunli.cterminal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.shunli.cterminal.entity.SystemShipChannelLink;
import com.shunli.cterminal.enums.JumpFlagEnum;
import com.shunli.cterminal.mapper.SystemShipWayDetailMapper;
import com.shunli.cterminal.model.bo.ShipDetailBO;
import com.shunli.cterminal.model.req.LinkQueryReq;
import com.shunli.cterminal.model.res.JumpLinkVO;
import com.shunli.cterminal.service.ShipWayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ShipWayServiceImpl implements ShipWayService {

    private final SystemShipWayDetailMapper shipWayDetailMapper;

    @Override
    public JumpLinkVO queryLink(LinkQueryReq req) {
        // 处理时间
        LocalDateTime now = LocalDateTime.now();
        String currDate = now.toLocalDate().toString();
        String currTime = now.toLocalTime().toString();
        String currWeek = String.valueOf(LocalDateTimeUtil.dayOfWeek(now.toLocalDate()).getIso8601Value());
        List<ShipDetailBO> boList = shipWayDetailMapper.queryEligibleData(req.getGoodsId(), currDate, currTime, currWeek,req.getProductType(),req.getProjectCode(), req.getChannelType());
        if (CollectionUtil.isEmpty(boList)) {
            return null;
        }
        boList = boList.stream()
                .sorted(Comparator.comparing(ShipDetailBO::getType).reversed().thenComparing(ShipDetailBO::getSort))
                .collect(Collectors.toList());
        ShipDetailBO bo = boList.get(0);
        JumpLinkVO vo = new JumpLinkVO();
        vo.setJumpFlag(bo.getJumpFlag());
        vo.setShipWay(bo.getJumpWay());
        if(!StrUtil.equals(bo.getJumpFlag(), JumpFlagEnum.AUTO_JUMP.getCode())) {
            List<SystemShipChannelLink> linkList = shipWayDetailMapper.queryShipLink(bo.getJumpWay(), req.getProductType(), req.getProjectCode(), req.getChannelType());
            if (CollectionUtil.isEmpty(linkList)) {
                return null;
            }
            SystemShipChannelLink link = linkList.get(RandomUtil.randomInt(linkList.size()));
            vo.setLink(link.getLink());
            vo.setSaleWxCustomerAcquisitionId(link.getSaleWxCustomerAcquisitionId());
        }
        return vo;
    }
}
